<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/11/6
 * Time: 12:49
 */

require DXW_TXCDN_DIR.'autoload.php';
class TxCdn{
    private $buckets = "";
    private $cosClient = null;
    public function __construct(){
        $this->buckets = DXW_TXCDN_BUCKETS;
        $this->cosClient = new Qcloud\Cos\Client(array(
            'region' => DXW_TXCDN_REGION, #地域，如ap-guangzhou,ap-beijing-1
            'credentials' => array(
                'secretId' => DXW_TXCDN_SECRETID,
                'secretKey' => DXW_TXCDN_SECRETKEY,
            ),
        ));
    }
    static $distince = null;
    public static function create(){
        if(null === self::$distince){
            self::$distince = new self;
        }
        return self::$distince;
    }

    public function upload($filename,$fmt=null){
        $bucket = $this->buckets;
        $key = md5($filename).($fmt);
        try{
            $body =  fopen($filename, 'rb');
        }catch(Exception $e){
            echo " Can't open file.{$e}";
            exit();
        }
        try {
            $result = $this->cosClient->putObject(array(
                'Bucket' => $bucket,
                'Key' => $key,
                'Body' => $body,
            ));
            //上传完成,删除本地文件
            unlink($filename);
            //取值方式 $result["ObjectURL"];用于保存
           return $result;
        } catch (\Exception $e) {
            return [];
        }
    }
}